import { Component, OnInit, Host, ViewChild } from '@angular/core';
import { AppComponent } from '../../../app.component';
import { AccountsService } from '../accounts/accounts.service';
import { Page } from '../../../shared/components/table/models/pagination.model';
import { TableRouterLink } from '../../../shared/components/table/models/tableRouterLink.model';
import { PaginationPositionDisplayEnum, TableComponent } from '../../../shared/components/table/table.component';
import { ColumnOptions, ColumnType } from '../../../shared/components/table/models/columnOptions.model';
import { StatusEnum } from '../models/user.model';
import { TableOptions } from '../../../shared/components/table/models/tableOptions.model';

@Component({
  templateUrl: './ip-login.component.html',
  styleUrls: ['./ip-login.component.scss'],
  providers: [AccountsService]
})
export class IpLoginComponent implements OnInit {
  public paginationPosition = PaginationPositionDisplayEnum.UpAndDown;
  public columns: ColumnOptions[] = [
    new ColumnOptions('name', 'Account Name', 'col-md-8', true, ColumnType.Link),
    new ColumnOptions('status', 'Status', 'col-md-4', false, ColumnType.Label)
  ];

  public accounts: any[];
  public count: number;
  public crmSynDate: string;
  public filter: any = { name: '' };
  public statuses: typeof StatusEnum = StatusEnum;
  public selectedStatus: string = StatusEnum[StatusEnum.All];
  @ViewChild('accountsTable') accountsTable: TableComponent;
  private options: TableOptions;

  constructor(@Host() private rootComponent: AppComponent,
    private accountsService: AccountsService) { }

  ngOnInit() {
    this.options = new TableOptions('name');
    this.options.filter = this.filter;
    this.getAccounts();
    this.accountsService.getLastCRMSyncDate().subscribe(data => {
      this.crmSynDate = data;
    });
  }

  public getAccounts(listOnly: boolean = false) {
    if (listOnly == false) {
      if (this.options.pageOptions.skip > 0) this.accountsTable.pageChanged(new Page(0, 20));
      this.accountsService.getAccountsCount(this.options.filter.name, this.selectedStatus).subscribe(data => {
        this.count = data;
      });
    }

    this.accountsService.getAccountsList(this.options.filter.name, this.selectedStatus, this.options.pageOptions.skip, this.options.pageOptions.take).subscribe(data => {
      this.accounts = data.map(account => {
        return {
          name: new TableRouterLink(account.name, true, [account.id, account.name]),
          status: account.status
        }
      });
      this.rootComponent.finishLoading();
    });
  }

  public tableOptionsChanged(tableOptions: TableOptions) {
    this.options = tableOptions;
    this.getAccounts(tableOptions.pageOptions.listOnly);
  }
}
